<template>
  <t-card :bordered="false">

    <!-- 自定义表格 -->
    <custom-table 
      ref="customTableRef" 
      row-key="id" 
      :columns="columns" 
      :api="budgeModelSumCRUD.page"
      :on-before-set-data="handleTableSetData"
      max-height="calc(100vh - 280px)"
      fixed-page-size
      >
      <template #topContent>
        <div style="margin-bottom: var(--td-comp-margin-xxl)">
          <t-radio-group v-model="defaultType"   @change="handleTypeChange">
            <t-radio-button v-for="_ in typeList" :key="'report'+_.value" :value="_.value"> {{ _.name }}</t-radio-button>
          </t-radio-group>

          <t-tabs v-model:value="selectedTab" :list="list"  @change="handleInitTable" v-if="selectedTab!=3">
            <template #action>
           <t-button 
            theme="primary" 
            variant="text"  
            v-permission="['system:budget-model-sum:create']" 
            @click="handleOpenDialog('create', { 
              modelId: props.modelId, 
              sumType:selectedTab, 
              contentType: defaultType, 
              bindReduceId: [], 
              unitReduceId: [], 
              countType:selectedTab==3?'3':'',
              moneyType:selectedTab==3?'1':'',
              unit:selectedTab==3?'11':''
            })">
              <template #icon><add-icon /></template>
              添加汇总
            </t-button>
          
            </template>
          </t-tabs>
          
          <t-tabs v-model:value="selectedTab" :list="list"  @change="handleInitTable" v-else>
            <template #action>
           <t-button 
            theme="primary" 
            variant="text"  
            v-permission="['system:budget-model-sum:create']" 
            @click="visibleGift=true">
              <template #icon><add-icon /></template>
              添加汇总
            </t-button>
          
            </template>
          </t-tabs>
          <!-- <t-tabs v-model:value="selectedTab" :list="hiddenList"  @change="handleInitTable"  class="hidden" v-else>
            <template #action>
           <t-button 
            theme="primary" 
            variant="text" 
            v-permission="['system:budget-model-sum:create']"
            @click="handleOpenDialog('create', { 
              modelId: props.modelId, 
              sumType:selectedTab, 
              contentType: defaultType, 
              bindReduceId: [], 
              unitReduceId: []
            })">
              <template #icon><add-icon /></template>
              添加汇总
            </t-button>
          
            </template>
          </t-tabs> -->

        </div>
      </template>
      <template #unit="{ row }">
        {{ dictionaryStore.analysis('unit', row.unit) }}
      </template>
      <template #operation="{ row }">
        <t-space break-line>
          <t-link
            v-permission="['system:budget-model-sum:update']"
            theme="primary"
            @click="handleOpenDialog('update', { id: row.id })"
          >
            编辑
          </t-link>
         
          <t-popconfirm content="确认要删除该项吗？" @confirm="handleDelete({ id: row.id })">
            <t-link v-permission="['system:budget-model-sum:delete']" theme="danger"> 删除 </t-link>
          </t-popconfirm>
        </t-space>
      </template>
     
      
      

    </custom-table>
    <!-- 自定义对话框 -->
    <custom-dialog
      ref="customDialogRef"
      v-slot="{ formData, readonly }"
      :api-map="budgeModelSumCRUD"
      header="*"
      :on-before-save-data="handleDialogSaveData"
      :on-before-set-data="handleDialogSetData"
      @request-success="handleDialogRequestSuccess"
    >
      <t-form-item label="细则名称" name="name" :rules="[{ required: true, message: '请输入细则名称' }]">
        <t-input v-model:value="formData.name" placeholder="请输入细则名称" clearable :readonly="readonly||formData.sumType==3" />
      </t-form-item>
      <t-form-item label="单位" name="unit" :rules="[{ required: true, message: '请选择单位' }]">
        <t-select
          v-model:value="formData.unit"
          :options="dictionaryStore.get('unit')"
          placeholder="请选择单位"
          clearable
          filterable
          :readonly="readonly||formData.sumType==3"
          @clear="formData.unit = null"
        />
      </t-form-item>
      <t-form-item label="数量" name="number" :rules="[{ required: true, message: '请输入数量' },{  min: 0, message: '数量不能小于0' }]">
        <t-input-number :decimal-places="2" :min="0" v-model:value="formData.number" placeholder="请输入数量" clearable :readonly="readonly" style="width: 100%;"/>
      </t-form-item>
      <t-form-item label="金额类型" name="moneyType" :rules="[{ required: true, message: '请选择金额类型' }]">
        <t-radio-group v-model:value="formData.moneyType" :readonly="readonly||formData.sumType==3">
          <t-radio
            v-for="_ in typeOption"
            :key="_.value"
            :value="_.value"
            
          >
            {{ _.label }}
          </t-radio>
        </t-radio-group>
      </t-form-item>
      <t-form-item label="价格获取方式" name="countType" :rules="[{ required: true, message: '请选择价格获取方式' }]">
        <t-radio-group v-model:value="formData.countType" :readonly="readonly||formData.sumType==3" @change="handleCountType">
          <t-radio
            v-for="_ in countTypeOption"
            :key="_.value"
            :value="_.value"
            
          >
            {{ _.label }}
          </t-radio>
        </t-radio-group>
      </t-form-item>
      <t-form-item label="单价(元)" name="unitPrice"  v-if="['3'].includes(formData.countType)" :rules="[{ required: true, message: '请输入单价(元)' },{  min: 0, message: '单价不能小于0' }]">
        <t-input-number :decimal-places="2" :min="0" v-model:value="formData.unitPrice" placeholder="请输入单价(元)" clearable :readonly="readonly||formData.sumType==3" style="width: 100%;" />
      </t-form-item>
      <t-form-item label="单价(元)" name="unitReduceId"  v-if="['2'].includes(formData.countType)" :rules="[{ required: true, message: '请输入单价(元)' }]">
        <t-select v-model:value="formData.unitReduceId" clearable filterable placeholder="" multiple>
            <t-option v-for="_ in unitPriceList" :key="_.id" :value="_.id" :label="`${_.name}-${ _.totalPrice}`">
              {{ _.name }}-{{ _.totalPrice }}
            </t-option>
          </t-select>
      </t-form-item>
      <t-form-item label="单价(元)" name="unitReduceId"  v-if="['1'].includes(formData.countType)" :rules="[{ required: true, message: '请输入单价(元)' }]">
        <t-select v-model:value="formData.unitReduceId" clearable filterable placeholder="" multiple>
            <t-option v-for="_ in unitPriceList" :key="_.id" :value="_.id" :label="`${_.name}-${ _.totalPrice}`">
              {{ _.name }}-{{ _.totalPrice }}
            </t-option>
          </t-select>
      </t-form-item>
    </custom-dialog>
    <discuss-gift-selector-dialog
      v-model:visible="visibleGift"
      :single="true"
      @save="handleSaveGift" />
  </t-card>
</template>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin, TableCol } from 'tdesign-vue-next';
import { AddIcon } from 'tdesign-icons-vue-next';
import { computed, onMounted, onUpdated, Ref, ref, useTemplateRef, watch } from 'vue';

import { budgeModelSheetCRUD, budgeModelSumCRUD } from '@/api/budget/model';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';

import { useDictionaryStore, useUserStore } from '@/store';
import { getUserListByRoleCode } from '@/api/system/user';
import listToTree from '@/utils/listToTree';
import disposableParams from '@/utils/disposableParams';
import DiscussGiftSelectorDialog from './DiscussGiftSelectorDialog.vue';
const props = defineProps({
  modelId: {
    type: Number,
    required: true,
  },
});
const emits = defineEmits(['typeChange']);
// 字典仓库
const dictionaryStore = useDictionaryStore();
// 用户仓库
const userStore = useUserStore();
// 分类汇总
const typeList = [
  {value:1,name:'基础套餐'},
  // {value:2,name:'个性化部分'},
  ]
// 分类默认
const defaultType = ref(1)

const selectedTab = ref(1)
const list = [{
  label:'套餐内容', value:1
},{
  label:'个性化部分', value:4
},{
  label:'优惠纪要', value:2
},{
  label:'赠送项目', value:3
}]
// 选择赠品
const visibleGift = ref(false)
const hiddenList = ref([{ label: '', value: '', destroyOnHide: true }]);
const typeOption = [{label:'小计', value:'1'},{label:'总计', value:'2'}]
const countTypeOption = [{label:'sheet获取', value:'1'},{label:'细则获取', value:'2'},{label:'自定义', value:'3'}]
const table = ref([])
// 处理表格设置数据
const handleTableSetData = (data: any) => {
  table.value = data
  return data;
};

// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// columns
const columns: TableCol[] = [
    { colKey: 'name', title: '细则名称',width:300 },
    { colKey: 'unit', title: '单位' },
    { colKey: 'number', title: '数量' },
    { colKey: 'unitPrice', title: '单价(元)' },
    { colKey: 'totalPrice', title: '总价(元)' },
    { colKey: 'operation', title: '操作', width: 180, fixed: 'right' },

];

// 处理初始化表格
const handleInitTable = () => {
  // 待办树跳转参数
  const toDoTreeJumpParams = disposableParams.get('to-do-tree-jump-params');
  const params:any = {
    modelId: props.modelId,
    contentType: defaultType.value,
  }
  if (defaultType.value !== 2) {
    params.sumType = selectedTab.value;
  }
  customTableRef.value.initTable(params);
};
// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};
onMounted(() => {
  handleInitTable()
});
// 监听 modelId 变化
watch(() => props.modelId, () => {
  selectedTab.value = 1
  defaultType.value = 1
  emits('typeChange',defaultType.value)
  handleInitTable(); // 当 modelId 改变时重新初始化表格
});

// 分类汇总改变
const handleTypeChange = () => {
  handleInitTable()
  emits('typeChange',defaultType.value)
}
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'create') handleInitTable();
  if (result.mode === 'update') handleRefreshTable();
};
// 处理删除
const handleDelete = (params: Record<string, any>) => {
  budgeModelSumCRUD
    .delete(params)
    .then(() => {
      MessagePlugin.success('删除成功');
      handleRefreshTable();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  customDialogRef.value.open(mode, params);
};
// 细则信息列表
const unitPriceList = ref([]);
// 处理获取细则信息列表
const handleGetUnitPriceList = () => {
  const params = {
    pageSize: -1,
    modelId: props.modelId
  };
  budgeModelSumCRUD
    .page(params)
    .then((data) => {
      unitPriceList.value = data.list;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 处理获取sheet信息列表
const handleGetSheetList = () => {
  const params = {
    pageSize: -1,
    contentType: defaultType.value,
    modelId: props.modelId
  };
  budgeModelSheetCRUD
    .page(params)
    .then((data) => {
      unitPriceList.value = data;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 处理对话框设置数据
const handleDialogSetData = (params: Record<string, any>) => {
 if(params.countType==='2') {
    handleGetUnitPriceList()
    params.unitReduceId = params.bindingId
 }
 if(params.countType=== '1') {
    handleGetSheetList()
    params.unitReduceId = params.bindingId
 }
};
// 处理对话框保存数据
const handleDialogSaveData =(params: Record<string, any>)=>{
  if(params.countType==='2'||params.countType==='1') {
    if(params.unitReduceId) {
      params.bindingId = params.unitReduceId
      params.unitPrice = params.unitReduceId.reduce((total: any, id: any) => {
      const selectedItem = unitPriceList.value.find(item => item.id === id);
      return total + (selectedItem?.totalPrice || 0);
    }, 0);
  }
  } 
};
const handleCountType = (checkedValues:any) => {
  if(checkedValues==='1') {
    handleGetSheetList()
  }
  if(checkedValues === '2') {
    handleGetUnitPriceList()
  }
  
}
// 处理保存赠品数据方法
const handleSaveGift= (selectedData: any[]) => {
  handleOpenDialog('create', { 
              modelId: props.modelId, 
              sumType:selectedTab.value, 
              contentType: defaultType.value, 
              countType:'3',
              moneyType:'1',
              unit:'11',
              name:selectedData[0].name,
              unitPrice:selectedData[0].money,
              giftId:selectedData[0].giftId,
              remark:selectedData[0].remark,
            })
}
defineExpose({
  refreshTable: handleRefreshTable,
});
</script>

<style lang="less" scoped>
:deep(.t-tabs__operations--right) {
  top: 15px;
}
:deep(.hidden .t-tabs__nav-item-text-wrapper) {
  visibility: hidden;
}
</style>
